package com.geekcoding.geekoj.controller.admin;

import cn.hutool.crypto.SecureUtil;
import com.geekcoding.common.dto.ApiResponse;
import com.geekcoding.geekoj.dto.User;
import com.geekcoding.geekoj.dto.request.ChangePwd;
import com.geekcoding.geekoj.dto.request.UserSaveOrUpdateReq;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.mapper.UserEntityMapper;
import com.geekcoding.geekoj.repository.UserEntityRepository;
import com.geekcoding.geekoj.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController()
@RequestMapping("/api/admin/user")
public class AdminUserController extends BaseAdminController<UserEntity, User, UserEntityMapper, UserEntityRepository>{

    public AdminUserController(UserEntityRepository repository, UserService userService) {
        super(repository, userService);
    }

    @PostMapping("/changePassword")
    public ApiResponse changePwd(@RequestBody ChangePwd rpo) {
        userService.checkAdminUser();
        UserEntity userEntity = repository.getById(rpo.getId());
        userEntity.setPassword(SecureUtil.md5(rpo.getPassword() + userEntity.getSalt()));
        repository.saveOrUpdate(userEntity);
        return ApiResponse.success(User.of(userEntity, null));
    }

    @PostMapping("/edit")
    public ApiResponse saveOrUpdate(@RequestBody UserSaveOrUpdateReq rpo) {
        userService.checkAdminUser();
        return ApiResponse.success(repository.convert(repository.addOrUpdate(rpo)));
    }
}
